package com.knowledgegraph.controller;

import com.knowledgegraph.common.Result;
import com.knowledgegraph.common.ResponseCode;
import com.knowledgegraph.dto.LoginRequest;
import com.knowledgegraph.dto.RegisterRequest;
import com.knowledgegraph.entity.User;
import com.knowledgegraph.service.UserService;
import com.knowledgegraph.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 * 
 * @author system
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@Validated
public class AuthController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@Valid @RequestBody LoginRequest request, 
                                           HttpServletRequest httpRequest) {
        try {
            String loginIp = IpUtil.getClientIp(httpRequest);
            String token = userService.login(request.getUsername(), request.getPassword(), loginIp);
            
            User user = userService.findByUsername(request.getUsername());
            
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("user", getUserInfo(user));
            
            return new Result<>(ResponseCode.AUTH_SUCCESS, "登录成功", data);
        } catch (Exception e) {
            log.error("用户登录失败: {}", e.getMessage());
            
            // 根据异常类型返回不同的错误码
            if (e.getMessage().contains("用户不存在")) {
                return new Result<>(ResponseCode.USER_NOT_FOUND, "用户不存在");
            } else if (e.getMessage().contains("密码错误")) {
                return new Result<>(ResponseCode.PASSWORD_ERROR, "密码错误");
            } else if (e.getMessage().contains("账户被锁定")) {
                return new Result<>(ResponseCode.ACCOUNT_LOCKED, "账户已被锁定");
            } else if (e.getMessage().contains("账户被禁用")) {
                return new Result<>(ResponseCode.ACCOUNT_DISABLED, "账户已被禁用");
            } else {
                return new Result<>(ResponseCode.AUTH_FAILED, "登录失败：" + e.getMessage());
            }
        }
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<String> register(@Valid @RequestBody RegisterRequest request) {
        try {
            User user = new User();
            BeanUtils.copyProperties(request, user);
            
            boolean success = userService.register(user);
            if (success) {
                return new Result<>(ResponseCode.SUCCESS, "注册成功");
            } else {
                return new Result<>(ResponseCode.OPERATION_FAILED, "注册失败");
            }
        } catch (Exception e) {
            log.error("用户注册失败: {}", e.getMessage());
            
            // 根据异常类型返回不同的错误码
            if (e.getMessage().contains("用户名已存在")) {
                return new Result<>(ResponseCode.USERNAME_EXISTS, "用户名已存在");
            } else if (e.getMessage().contains("邮箱已存在")) {
                return new Result<>(ResponseCode.EMAIL_EXISTS, "邮箱已存在");
            } else {
                return new Result<>(ResponseCode.OPERATION_FAILED, "注册失败：" + e.getMessage());
            }
        }
    }

    /**
     * 检查用户名是否可用
     */
    @PostMapping("/check-username")
    public Result<Boolean> checkUsername(@RequestBody Map<String, Object> params) {
        String username = (String) params.get("username");
        User user = userService.findByUsername(username);
        return Result.success(user == null);
    }

    /**
     * 检查邮箱是否可用
     */
    @PostMapping("/check-email")
    public Result<Boolean> checkEmail(@RequestBody Map<String, Object> params) {
        String email = (String) params.get("email");
        User user = userService.findByEmail(email);
        return Result.success(user == null);
    }

    /**
     * 重置密码
     */
    @PostMapping("/reset-password")
    public Result<String> resetPassword(@RequestBody Map<String, Object> params) {
        String email = (String) params.get("email");
        try {
            boolean success = userService.resetPassword(email);
            if (success) {
                return Result.success("密码重置成功，新密码已发送到您的邮箱");
            } else {
                return Result.error("密码重置失败");
            }
        } catch (Exception e) {
            log.error("密码重置失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取用户信息（去除敏感信息）
     */
    private Map<String, Object> getUserInfo(User user) {
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", user.getId());
        userInfo.put("username", user.getUsername());
        userInfo.put("nickname", user.getNickname());
        userInfo.put("email", user.getEmail());
        userInfo.put("phone", user.getPhone());
        userInfo.put("avatar", user.getAvatar());
        userInfo.put("gender", user.getGender());
        userInfo.put("role", user.getRole());
        userInfo.put("status", user.getStatus());
        return userInfo;
    }
}